package com.scnu.gateway.filters;

import com.scnu.common.constants.HttpStatusConstants;
import com.scnu.gateway.client.UserService;
import com.scnu.gateway.config.AuthProperties;
import com.scnu.gateway.util.JwtTool;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

@Component
@RequiredArgsConstructor
@Slf4j
public class AuthGlobalFiler implements GlobalFilter, Ordered {

    private final AuthProperties authProperties;

    private final JwtTool jwtTool;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();


//    private final UserClient userClient;
    private final UserService userService;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        if (isExcludePath(request.getPath().toString())){
            return chain.filter( exchange);
        }
        String token = null;
        List<String> headers = request.getHeaders().get("Authorization");
        if (headers != null && !headers.isEmpty()){
            token = headers.get(0);
        }
//        Long userId = null;
        Map<String, String> tokenMap;
        try {
            tokenMap = jwtTool.parseToken(token);
        } catch (Exception e) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        String userId = tokenMap.get("userId");
        String acquisitionTimeStr = tokenMap.get("acquisitionTime");
        LocalDateTime acquisitionTime = LocalDateTime.parse(acquisitionTimeStr, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
//        LocalDateTime logoutTime =
        return userService.getUserLogoutTime(Long.valueOf(userId))
                .doOnError(e -> {
                    // 日志记录错误
                    System.err.println("Error fetching user logout time: " + e.getMessage());

                })
                .flatMap(result ->{
                    LocalDateTime logoutTime;
                    if (result.getCode()!= HttpStatusConstants.SUCCESS){
                        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                        return exchange.getResponse().setComplete();
                    }
                    logoutTime = LocalDateTime.parse(result.getData().toString(), DateTimeFormatter.ISO_LOCAL_DATE_TIME);
//                    log.info("logoutTime：{}",logoutTime);
                    if (logoutTime.isAfter(acquisitionTime)) {
                        // 正确的响应式错误处理方式
                        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                        return exchange.getResponse().setComplete();
                    }
//                    log.info("userId:{}",tokenMap.get("userId"));

                    ServerWebExchange build = exchange.mutate().request(builder ->{
                        builder.header("user-id", userId);
//                        builder.header("acquisition-time",acquisitionTimeStr);
                    }).build();
                    return chain.filter( build);
                });


//
//        return chain.filter( build);
    }

    private boolean isExcludePath(String path) {
        for (String excludePath : authProperties.getExcludePaths()) {
            if (antPathMatcher.match(excludePath, path)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}